package com.crm.services;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.model.jdao.ISalesOpportunityDAO;
import com.crm.model.jdao.ISalesTrackingLogDAO;
import com.crm.model.jdao.IShowsettingSalesOpportunityDAO;
import com.crm.model.pojo.Contact;
import com.crm.model.pojo.Customer;
import com.crm.model.pojo.SalesOpportunity;
import com.crm.model.pojo.SalesOpportunityTrackingLog;
import com.crm.model.pojo.ShowsettingSalesOpportunity;

@Service
public class SalesOpportunityServices {

	@Autowired
	private ISalesOpportunityDAO salDAO;
	@Autowired
	private SalesOpportunityServices ss;
	@Autowired
	private DictionaryServices ds;
	@Autowired
	private UserServices us;	
	@Autowired
	private IShowsettingSalesOpportunityDAO sssDAO;	
	@Autowired
	private ISalesTrackingLogDAO salLogDAO;
	private static int count=0;

	/**
	 * 销售机会新增
	 * @param sale
	 * @return
	 */
	public int save(SalesOpportunity newsale) {
		int a=0;
		int b=0;
		SalesOpportunity oldsale=salDAO.findBySalId(newsale.getSalId());
		if(null!=oldsale) {
			a=oldsale.getSalStage();
			b=newsale.getSalStage();			
		}
		System.out.println("旧的销售对象是："+a);
		System.out.println("新的销售对象是："+b);
	System.out.println("停留:"+newsale.getSalStageStop());
		if(oldsale==null) {
			newsale.setSalStageStop(0);
			salDAO.save(newsale);	
		}else {
			System.out.println("是否相等："+newsale.equals(oldsale));	
			
			if(!newsale.equals(oldsale)) {
				//查询传入的销售阶段是否等于数据库的销售阶段		
				if(a!=b) {
					//将阶段停留时间重置为0
					newsale.setSalStageStop(0);	
					//销售阶段被修改，这里新增一条销售机会跟踪日志
					SalesOpportunityTrackingLog salLog=new SalesOpportunityTrackingLog();	
					salLog.setSalesOpportunity(newsale);
					salLog.setSotlDate(newsale.getSotlDate());
					salLog.setSotlMoney(newsale.getSotlMoney());					
					salLog.setSotlName(newsale.getSotlId());
					salLog.setSotlPossibility(newsale.getSalPossibility());
					salLog.setSotlStage(newsale.getSalStage());
					salLog.setUpdateTime(newsale.getSalUpdatetime());
					salLog.setNotes(newsale.getSalStageNotes());
					salLogDAO.save(salLog);
				}
				//更新时间不是，查看一下就更新
				//再第一次新建的时候，时间是当前时间，查看不用更新当前时间
				//不用每次都保存，只有信息修改的时候才出发保存	
				salDAO.save(newsale);	
				
			}
		}
	
		return 1;		
	}
	/**
	 * 
	 * @param pageNumber  从那天开始显示
	 * @param pageContent 显示的记录条数
	 * @return
	 */
	public List<SalesOpportunity> queryByAll(int pageNumber,int pageContent,String[] DId){
		Sort sort=Sort.by(Direction.DESC, "salId");
		Pageable pageable =PageRequest.of(pageNumber,pageContent,sort);	
		//查询条件构造
		 Specification<SalesOpportunity> spec=new Specification<SalesOpportunity>(){

			@Override
			public Predicate toPredicate(Root<SalesOpportunity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				//Path<Object> state=root.get("state");
				List<Predicate> list=new ArrayList<>();
				System.out.println("ss的DId:"+DId);
					if(DId.length==0) {
						list.add(cb.equal(root.get("state").as(Integer.class), 1));
					}
					int i=0;
					for (String str : DId) {
						System.out.println("str:"+str);
						if("全部数据".equals(str)) {
							 list.add(cb.equal(root.get("state").as(Integer.class), 1));	
						}
						if("来源".equals(str)) {
							System.out.println("触发了来源数据筛选");
							 list.add(cb.equal(root.get("salSource").as(Integer.class), DId[i+1]));							
						}
						if("可能性".equals(str)) {
							System.out.println("触发了可能性数据筛选");
							 list.add(cb.equal(root.get("salPossibility").as(Integer.class), DId[i+1]));								
						}
						if("销售阶段".equals(str)) {
							System.out.println("触发了销售阶段数据筛选");
							 list.add(cb.equal(root.get("salStage").as(Integer.class), DId[i+1]));								
						}
						if("客户名称".equals(str)) {
							System.out.println("触发了模糊客户名称数据筛选");	
							//cb.countDistinct(root.join("customer").get("custName")));
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.join("customer").get("custName").as(String.class),"%"+DId[i+2]+"%"));									
							}else {
								list.add(cb.like(root.join("customer").get("custName").as(String.class),"%"+DId[i+1]+"%"));
							    query.groupBy(root.get("customer").as(Customer.class));
							}

						}
						if("联系人".equals(str)) {
							System.out.println("触发了模糊联系人负责人数据筛选");	
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.join("contact").get("conName").as(String.class),"%"+DId[i+2]+"%"));								
							}else {
								list.add(cb.like(root.join("contact").get("conName").as(String.class),"%"+DId[i+1]+"%"));
							    query.groupBy(root.get("contact").as(Contact.class));
							}

							//cb.countDistinct(root.join("customer").get("custName")));
							
						}
						if("机会主题".equals(str)) {
							System.out.println("触发了模糊机会主题数据筛选");	
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.get("salTheme").as(String.class),"%"+DId[i+2]+"%"));									
							}else {
								list.add(cb.like(root.get("salTheme").as(String.class),"%"+DId[i+1]+"%"));	
							}							
													
						}
						i++;
					}

		        Predicate[] p = new Predicate[list.size()];
		        System.out.println("-----------------------------------------");
			    query.where(list.toArray(p));
				return query.getRestriction();
			}
			 
		 };
		Page<SalesOpportunity> page =salDAO.findAll(spec,pageable);		
		System.out.println("总记录数："+page.getTotalElements());
		count=(int) page.getTotalElements();
		List<SalesOpportunity> list=page.getContent();
		return list;		
	}
	
	/**
	 * 总页数
	 * @param pageNumber
	 * @param pageContent
	 * @return
	 */
	/*public int AllPageNumber(int pageNumber,int pageContent) {
		Sort sort=Sort.by(Direction.DESC, "salId");
		Pageable pageable =PageRequest.of(pageNumber,pageContent,sort);
				//PageRequest.of(page, size, sort);
				//PageRequest(pageNumber,pageContent,) 		
		Page<SalesOpportunity> page =salDAO.findAll(pageable);
		System.out.println("总页数："+page.getTotalPages());
		return page.getTotalPages();
		
	}*/
	/**
	 *将list的数据转换成JsonArray的数据
	 * @return
	 */
	public JSONArray ListTransJSONArray(int pageNumber,int pageContent,String[] DId) {
		JSONArray array =new JSONArray();
		List<SalesOpportunity> list=ss.queryByAll(pageNumber,pageContent,DId);
		for (SalesOpportunity salesOpportunity : list) {
		//System.out.println("salesOpportunity:"+salesOpportunity);
			JSONObject obj = new JSONObject();		
			array.add(toJSONObject1( obj,salesOpportunity));
	}
		return array;
	}
	
	/**
	 * 销售机会转JSONObject
	 * @param obj
	 * @param salesOpportunity
	 * @return
	 */
	public JSONObject toJSONObject1(JSONObject obj,SalesOpportunity salesOpportunity) {
		obj.put("salId", salesOpportunity.getSalId());
		obj.put("salTheme", salesOpportunity.getSalTheme());
		obj.put("custName", salesOpportunity.getCustomer().getCustName());
		String starURL=ss.starURL(salesOpportunity.getStarStandard());
		obj.put("starStandard",starURL);
		obj.put("salType", ds.findByDictId(salesOpportunity.getSalType()));
		if(salesOpportunity.getSotlDate()!=null) {
			obj.put("sotlDate",salesOpportunity.getSotlDate().toString());			
		}				
		obj.put("sotlMoney", salesOpportunity.getSotlMoney());
		obj.put("custDemand", salesOpportunity.getCustDemand());
		obj.put("salStageStop", salesOpportunity.getSalStageStop()+"天");
		obj.put("salState",salesOpportunity.getSalState());
		obj.put("salSource", ds.findByDictId(salesOpportunity.getSalSource()));
		obj.put("sotlId", ss.findByUserName(salesOpportunity.getSotlId()));
		obj.put("salState", ds.findByDictId(salesOpportunity.getSalState())+"");		
		obj.put("salPossibility", ds.findByDictId(salesOpportunity.getSalPossibility()));
		obj.put("salUpdatetime", salesOpportunity.getSalUpdatetime().toString());
		//obj.put("", value);
		return obj;
	}
	
	/**
	 * 将list的数据转换成JsonArray的数据,用于页面搜索查询客户信息
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray1(List<SalesOpportunity> list) {
		JSONArray array = new JSONArray();
		for (SalesOpportunity salesOpportunity : list) {
			// System.out.println("salesOpportunity:"+salesOpportunity);
			JSONObject obj = new JSONObject();
			
			obj.put("value", salesOpportunity.getCustomer().getCustName());
			obj.put("label1", salesOpportunity.getCustomer().getCustId());
			array.add(obj);
		}
		return array;
	}	
	/**
	 * 将list的数据转换成JsonArray的数据,用于页面搜索查询负责人信息
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray2(List<SalesOpportunity> list) {
		JSONArray array = new JSONArray();
		for (SalesOpportunity salesOpportunity : list) {
			// System.out.println("salesOpportunity:"+salesOpportunity);
			JSONObject obj = new JSONObject();
			if(salesOpportunity.getContact()==null) {
				continue;
			}
			obj.put("value", salesOpportunity.getContact().getConName());
			obj.put("label1", salesOpportunity.getContact().getConId());
			array.add(obj);
		}
		return array;
	}	
	/**
	 * 将list的数据转换成JsonArray的数据,用于页面搜索查询销售机会主题名称信息
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray3(List<SalesOpportunity> list) {
		JSONArray array = new JSONArray();
		for (SalesOpportunity salesOpportunity : list) {
			// System.out.println("salesOpportunity:"+salesOpportunity);
			JSONObject obj = new JSONObject();
			obj.put("value", salesOpportunity.getSalTheme());
			array.add(obj);
		}
		return array;
	}
	
	/** 销售机会转JSONObject,单一saleOpp
	 * @param obj
	 * @param salesOpportunity
	 * @return
	 */
	public JSONObject toJSONObject2(JSONObject obj,SalesOpportunity salesOpportunity) {
		obj.put("salId", salesOpportunity.getSalId());
		obj.put("salTheme", salesOpportunity.getSalTheme());
		obj.put("customerName", salesOpportunity.getCustomer().getCustName());
		obj.put("customerId", salesOpportunity.getCustomer().getCustId()+"");			
		obj.put("starStandard",salesOpportunity.getStarStandard()+"");
		
		obj.put("salTypelabel", ds.findByDictId(salesOpportunity.getSalType()));
		obj.put("salTypeValue", salesOpportunity.getSalType());
		
		//obj.put("sotlId", salesOpportunity.getSotlId());	
		if(salesOpportunity.getSotlDate()!=null) {
			obj.put("sotlDate",salesOpportunity.getSotlDate().toString());			
		}		
		obj.put("sotlMoney", salesOpportunity.getSotlMoney());
		//
		obj.put("custDemand", salesOpportunity.getCustDemand());
		
		obj.put("salStageStop", salesOpportunity.getSalStageStop()+"天");		
		obj.put("salState", salesOpportunity.getSalState()+"");		
		obj.put("salPossibilitylabel", ds.findByDictId(salesOpportunity.getSalPossibility()));

		obj.put("sotlId", ss.findByUserName(salesOpportunity.getSotlId()));
		obj.put("salStagelabel", ds.findByDictId(salesOpportunity.getSalStage()));
		obj.put("salStageNotes", salesOpportunity.getSalStageNotes());
		
		obj.put("salSourcelabel", ds.findByDictId(salesOpportunity.getSalSource()));
		if(salesOpportunity.getContact()!=null) {
			obj.put("contactName", salesOpportunity.getContact().getConName()+"");			
		}else {
			obj.put("contactName","");				
		}
		obj.put("contactId", salesOpportunity.getContact().getConId());
		return obj;
	}
	
	
	/**
	 * 将star的数据转换成star图片地址
	 * @param star
	 * @return
	 */
	public String starURL(int star) {
		if(star==1317) {
			return "无";
		}else if(star==1318) {
			return "../imgs/sales/starBlue.png";			
		}else if(star==1319) {
			return "../imgs/sales/starGreen.png";			
		}else if(star==1320) {
			return "../imgs/sales/starPurple.png";			
		}else if(star==1321) {
			return "../imgs/sales/starRed.png";
		}else if(star==1322) {
			return "../imgs/sales/starYellow.png";			
		}else {
			
		}
		return null;		
	}
	
	/**
	 * 统计对象个数
	 * @return
	 */
	public int queryByCount() {
		return count;
		
	}
	  /**
	   * 根据id查询销售机会
	   * @param salId
	   * @return
	   */
	public  JSONObject findBySalId(Integer salId) {
		SalesOpportunity sale=salDAO.findBySalId(salId);
		JSONObject obj = new JSONObject();	
		return toJSONObject2(obj,sale);
		  
	  }
	/**
	 * 删除单个销售机会
	 * @param salId
	 * @return
	 */
	public void Delete(Integer salId) {
		SalesOpportunity sal=salDAO.findById(salId).get();
		sal.setState(0);
		salDAO.save(sal);		
	}
	
	/**
	 * 批量逻辑删除
	 * @param salIds
	 */
	public void DeleteAll(Iterable<Integer> salIds) {
		//Integer[] ff=new Integer[] {1,2,3};
		/*List list=new ArrayList();
		list.add(1);
		Iterable<Integer> dd=(Iterable<Integer>) list.iterator();
		ss.DeleteAll(dd);*/		
		Iterable<SalesOpportunity> a=salDAO.findAllById(salIds);
		for (SalesOpportunity salesOpportunity : a) {
			salesOpportunity.setState(0);
		}
		salDAO.saveAll(a);
	}
	
	/**
	 * 确认销售机会是否重复
	 * @param salTheme
	 * @return 
	 */
	public Integer findBySalTheme(String salTheme) {
		SalesOpportunity sale=salDAO.findBySalTheme(salTheme);
		if(sale!=null) {
			return sale.getSalId();
		}
		return 0;
	}
	
	/**
	 * 通过销售机会负责人id查询负责人名称
	 * @param sotlId
	 * @return
	 */
	private String findByUserName(Integer sotlId) {
		if(sotlId==null) {
			return "";
		}
		return us.findByUId(sotlId).getUName();		
	}
	/**
	 * 查询前台页面的显示字段
	 * @return
	 */
	public JSONObject showSalesSetting(int userID) {
		ShowsettingSalesOpportunity sss=sssDAO.findByUserId(userID);
		JSONObject obj=new JSONObject();
		return toJSONbject3(obj,sss);		
	}
	
	/**
	 * 
	 * @param info
	 */
	public void saveInfo(String[] info) {
		ShowsettingSalesOpportunity sss=new ShowsettingSalesOpportunity();
		/*
		 * 1.soltId:true",
		 * 2."Conid:true",
		 * 3."Cstdemand:false",
		 * 4."SalType:true",
		 * 5."Salfile:true",
		 * 6."Salpossibility:true",
		 * 7."Salsource:true",
		 * 8."Salstage:false", 
		 * 9."Salstagenotes:false",
		 * 10."Salstagestop:false", 
		 * 11."Salstate:true", 
		 * 12."Salupdatetime:true",
		 * 13."Sotlname:false"
		 */
		 
		sss.setSotlName(splitString(info,0));
		sss.setConId(splitString(info,1));		
		sss.setCustDemand(splitString(info,2));
		sss.setSalType(splitString(info,3));
		sss.setSalFile(splitString(info,4));		
		sss.setSalPossibility(splitString(info,5));
		sss.setSalSource(splitString(info,6));
		sss.setSalStage(splitString(info,7));
		sss.setSalStageNotes(splitString(info,8));		
		sss.setSalStageStop(splitString(info,9));	
		sss.setSalState(splitString(info,10));
		sss.setSalUpdatetime(splitString(info,11));		
		sss.setStarStandard(splitString(info,12));		
		//sss.setCustId(Integer.valueOf(info[1].split(":")[1].toString()));
		sss.setSotlMoney(splitString(info,13));
		sss.setSotlDate(splitString(info,14));
		sss.setUserId(splitString(info,15));						
		sss.setSetId(splitString(info,16));
		System.out.println("设置编号:"+sss.getSetId());
		System.out.println("看看是否添加成功:"+sssDAO.save(sss));
	}
	
	/**
	 * 分割string数组中的数组，并转换成Integer类型
	 * @param str
	 * @param i
	 * @return
	 */
	private int splitString(String[] str,int i) {
		return Integer.valueOf(str[i].split(":")[1]);
	}

	/**
	 * 这里处理前台数据显示的转JSONbject方法
	 * @param obj
	 * @return
	 */
	private JSONObject toJSONbject3(JSONObject obj,ShowsettingSalesOpportunity sss) {
		/*
		 *  					showSoltId:true,//这里设置字段是否显示,负责人
								showSalType:true,//类型
								showSotlDate:true;//预计签单日期
								showStarStandard:true;//星标
								showSotlMoney:true;//预期金额
								showSal_updatetime:true;//销售机会的更新时间
								showCon_id:true,//联系人名称
								showSal_state:true,// 销售状态
								showCst_demand :true,//客户需求
								showSal_possibility:true,//可能性
								showSal_source:true,//来源
								showSotl_name:true,//机会负责人名
								showSal_stage:true,//销售阶段
								showSal_stage_notes:true,//阶段备注
								showSal_stage_stop:true,//阶段停留
								showSal_file:true,//上传附件	
		 */
		if(null==sss) {
			obj.put("showSalType", 1);		
			obj.put("showSal_possibility", 1);
			obj.put("showSal_state",1);
			obj.put("showSal_source", 1);
			obj.put("showSal_updatetime", 1);	
			obj.put("showSoltId", 1);
			obj.put("showSotl_name", 0);
			obj.put("showSal_stage", 0);
			obj.put("showSal_stage_notes", 0);
			obj.put("showSal_stage_stop", 0);
			obj.put("showSal_file", 0);
			obj.put("showCon_id", 0);
			obj.put("showCst_demand",0);
			obj.put("showSotlDate", 0);
			
		}else {
			//obj.put("showSoltId", sss.);
			obj.put("setId",sss.getSetId());
			obj.put("showSalType", sss.getSalType());
			obj.put("showSotlDate", sss.getSotlDate());
			obj.put("showStarStandard", sss.getStarStandard());
			obj.put("showSotlMoney", sss.getSotlMoney());
			obj.put("showSal_updatetime", sss.getSalUpdatetime());
			obj.put("showCon_id", sss.getConId());
			obj.put("showSal_state", sss.getSalState());
			obj.put("showCst_demand", sss.getCustDemand());
			obj.put("showSal_possibility", sss.getSalPossibility());
			obj.put("showSal_source", sss.getSalSource());
			obj.put("showSotl_name", sss.getSotlName());
			obj.put("showSal_stage", sss.getSalStage());
			obj.put("showSal_stage_notes", sss.getSalStageNotes());
			obj.put("showSal_stage_stop", sss.getSalStageStop());
			obj.put("showSal_file", sss.getSalFile());
			obj.put("showSoltId", sss.getSotlName());
		
		}
		return obj;
		
	}
	
}
